package com.nbjtjc.safe.service.cost;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.nbjtjc.safe.bean.Result;
import com.nbjtjc.safe.mapper.cost.CostAccountRecordMapper;
import com.nbjtjc.safe.mapper.cost.CostAccountRegMapper;
import com.nbjtjc.safe.mapper.cost.CostBudgetItemMapper;
import com.nbjtjc.safe.mapper.cost.CostBudgetSubItemMapper;
import com.nbjtjc.safe.mapper.sys.SysDeptMapper;
import com.nbjtjc.safe.model.cost.CostAccountRecord;
import com.nbjtjc.safe.model.cost.CostAccountReg;
import com.nbjtjc.safe.util.MyShiroUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class CostAccountRegService {
	@Autowired
	  private CostAccountRegMapper costAccountRegMapper;
	@Autowired
	  private CostAccountRecordMapper costAccountRecordMapper;
	@Autowired
	  private CostBudgetItemMapper costBudgetItemMapper;
	@Autowired
	  private CostBudgetSubItemMapper costBudgetSubItemMapper;
    @Autowired
    private SysDeptMapper sysDeptMapper;
    
//  @Transactional(rollbackFor = {Throwable.class})
	  public Result add(CostAccountReg costAccountReg){
		        Result result=new Result();
		        if(ObjectUtil.isNull(costAccountReg)
		        		||ObjectUtil.isNull(costAccountReg.getBudgetPlanId())
		        		){		            
		        	result.setFalse("新增内容不能为空,关联预算计划不能为空");
		            return result;
		        }
		        //主键为空或库中无此主键则为新建，插入数据
		        if(ObjectUtil.isNull(costAccountReg.getId())|| ObjectUtil.isNull(costAccountRegMapper.selectByPrimaryKey(costAccountReg.getId()))){
			        //同样年份一直能有一个
			        if(ObjectUtil.isNotNull(costAccountReg.getYear())){
			        	CostAccountReg costAccountRegYear=new CostAccountReg();
			        	
			        	costAccountRegYear.setYear(costAccountReg.getYear());
			        	costAccountRegYear.setCompanyId(MyShiroUtils.getCompanyId());

			        	if(CollectionUtil.isNotEmpty(costAccountRegMapper.search(costAccountRegYear))){
				        	result.setFalse("该年份已有预算投入，不能重复增加");
				            return result;
			        	}
			        	
			        }else{
			        	result.setFalse("年份不能为空");
			            return result;
			        }
		        	
		        	int  companeyId= MyShiroUtils.getCompanyId();
		        	costAccountReg.setCompanyId(companeyId);
		        	costAccountReg.setCompanyName(sysDeptMapper.findNameById(companeyId));
		        	costAccountReg.setCreateDate(new Date());
		        	costAccountReg.setCreateId(MyShiroUtils.getSessionUserId());
			        
		        	int res=costAccountRegMapper.insertSelective(costAccountReg);
			        if(res==0){
			            result.setFalse("新建预算投入登记表失败");
			            return result;
			        }

		        }else
		        {
		        	costAccountReg.setModifyDate(new Date());
		        	costAccountReg.setModifyId(MyShiroUtils.getSessionUserId());
		        	int res=costAccountRegMapper.updateByPrimaryKeySelective(costAccountReg);
		        	 if(res==0){
		        		 result.setFalse("更新预算投入登记表失败");
				         return result;
		        	 }
		        	 boolean flag = CollectionUtil.isEmpty(costAccountReg.getCostAccountRecords());
		        	 if(CollectionUtil.isNotEmpty(costAccountReg.getCostAccountRecords())){
		        		 result  = updateCostAccountRecords(costAccountReg);
			        	 if(result.isSuccess()==false){
			        		 result.setFalse("更新预算投入项目失败");
					         return result;
			        	 }
		        	 }
		        	 
		        	 //更新预算投入登记表投入总额
		        	 res = costAccountRegMapper.updateTotalAccount(costAccountReg.getId());
		        	 if(res==0){
		        		 result.setFalse("更新预算投入登记表投入总额失败");
				         return result;
		        	 }
		        }
		        
		        result.setData(costAccountReg);

		        return result;
		    }

//	    private Result insertCostAccountRecords(CostAccountReg costAccountReg){
//	        Result result=new Result();
//
//	    	//将CostAccountRecords的budgetPlanId都设为当前costAccountReg的ID
//	    	List<CostAccountRecord> costAccountRecords =  costAccountReg.getCostAccountRecords();
//			for(CostAccountRecord costAccountRecord: costAccountRecords){
//				costAccountRecord.setAccountRegId(costAccountReg.getId());
//			}
//			
//	    	int res=costAccountRecordMapper.insertList(costAccountRecords);
//	    	if(res==0){
//	            result.setFalse("插入费用 投入项目失败");
//	            return result;
//	        }
//	    	result.setData(costAccountRecords);
//	    	return result;
//	    }
	    //更新记录子表
	    private Result updateCostAccountRecords(CostAccountReg costAccountReg){
	        Result result=new Result();
	    	if(CollectionUtil.isEmpty(costAccountReg.getCostAccountRecords())){
	            result.setFalse("更新对象为空");
	        	return result;
		    }
	    	ArrayList<Integer> costAccountRecordsIdDataBase = costAccountRecordMapper.findIdByRegId(costAccountReg.getId());
	    	ArrayList<Integer> costAccountRecordsId = new ArrayList();
	    	//将CostAccountRecords的budgetPlanId都设为当前costAccountReg的ID
	    	//若库中已有该项目（ID不为空，库中查得到）则更新，否则（该项目ID为空，或库中查不到）插入
	    	List<CostAccountRecord> costAccountRecords =  costAccountReg.getCostAccountRecords();
			for(CostAccountRecord costAccountRecord: costAccountRecords){
				//项目为空则跳过，继续下一个
				if(ObjectUtil.isNull(costAccountRecord)){
		            continue;
				}
				//如果ID不为空，加入costAccountRecordsId
				if(ObjectUtil.isNotNull(costAccountRecord.getId())){
					costAccountRecordsId.add(costAccountRecord.getId());
				}
				int res=0;
		    	//将CostAccountRecord的budgetPlanId设为当前costAccountReg的ID
				costAccountRecord.setAccountRegId(costAccountReg.getId());  
				//库中已有该项目（ID不为空，库中查得到）则更新
				if(ObjectUtil.isNotNull(costAccountRecord.getId()) && ObjectUtil.isNotNull(costAccountRecordMapper.selectByPrimaryKey(costAccountRecord.getId()))){
					res = costAccountRecordMapper.updateByPrimaryKeySelective(costAccountRecord);
					if(res==0){
			            result.setFalse("更新费用投入项目失败");
			            return result;
			        }
			    	//更新预算项目投入金额
			    	result = updateItemByRecord(costAccountRecord.getBudgetItemId());
		        	 if(result.isSuccess()==false){
		        		 result.setFalse("更新预算投入项目失败");
				         return result;
		        	 }
				}else{
					//（该项目ID为空，或库中查不到）插入
			    	res=costAccountRecordMapper.insertSelective(costAccountRecord);
			    	if(res==0){
			            result.setFalse("插入费用投入项目失败");
			            return result;
			        }
			    	//更新预算项目投入金额
			    	result = updateItemByRecord(costAccountRecord.getBudgetItemId());
		        	 if(result.isSuccess()==false){
		        		 result.setFalse("更新预算投入项目失败");
				         return result;
		        	 }
				}
			}
			//库中有而更新内容没有的项目的ID，是要删除的项目
			for(Integer id:costAccountRecordsIdDataBase){
				int res=-1;
				if(costAccountRecordsId.contains(id)==false){
					int subItemId = costAccountRecordMapper.selectByPrimaryKey(costAccountRecordsId).getBudgetItemId();
					res = costAccountRecordMapper.deleteByPrimaryKey(id);
			    	if(res==0){
			            result.setFalse("删除库中费用投入项目失败");
			            return result;
			        }
			    	//更新预算项目投入金额
			    	if(ObjectUtil.isNotNull(subItemId)){
				    	result = updateItemByRecord(subItemId);
			        	 if(result.isSuccess()==false){
			        		 result.setFalse("更新预算投入项目失败");
					         return result;
			        	 }
			    	}else{
			            result.setFalse("应删除的ID所查投入记录为空，操作失败");
			            return result;
			    	}
				}
			}
	    	result.setData(costAccountRecords);
	    	return result;
	    }
	  //更新相关预算项目和子项目投入金额
	  public Result updateItemByRecord(int subItemId){
	      Result result=new Result();
		  int res=-1;
		  //更新预算子项目投入总额
		 res = costBudgetSubItemMapper.updateAccountSum(subItemId);
	      if(res==0){
	    	  result.setFalse("更新子项目投入总额失败");
		      return result;
	      }
	    	//更新预算一级项目投入总额
		 res =  costBudgetItemMapper.updateAccountSum(subItemId);
	      if(res==0){
	    	  result.setFalse("更新预算项目投入总额失败");
		      return result;
	      }
	      return result;
	  }
	  @Transactional(rollbackFor = {Throwable.class})
	  public Result delete(int id){
	      Result result=new Result();
	      if(ObjectUtil.isNull(id)){
	          result.setFalse("删除对象不能为空");
	          return result;
	      }
	      //记录该id的预算投入涉及到的预算子项目
	      CostAccountReg costAccountReg = costAccountRegMapper.selectByPrimaryKey(id);
	      List<Integer> costBudgetSubItemIds = new ArrayList();
	      if(CollectionUtil.isNotEmpty(costAccountReg.getCostAccountRecords())){
		      List<CostAccountRecord> costAccountRecords = costAccountReg.getCostAccountRecords();
		      for(CostAccountRecord costAccountRecord:costAccountRecords){
		    	  costBudgetSubItemIds.add(costAccountRecord.getBudgetItemId());
		      }
	      }

	      //删除
	      int res = costAccountRegMapper.deleteByPrimaryKey(id);
	      if(res==0){
	    	  result.setFalse("删除失败");
		      return result;
	      }
	      if(CollectionUtil.isNotEmpty(costAccountReg.getCostAccountRecords())){
		      //更新各预算项目投入金额
		      for(Integer costBudgetSubItemId:costBudgetSubItemIds){
		    	  updateItemByRecord(costBudgetSubItemId);
		      }
	      }
	      
		 
	      return result;
	  }
	  
	  @Transactional(rollbackFor = {Throwable.class})
	  public Result delete(CostAccountReg costAccountReg){
	      Result result=new Result();
	      if(ObjectUtil.isNull(costAccountReg.getId())){
	          result.setFalse("作废对象不能为空");
	          return result;
	      }
	      int id = costAccountReg.getId();
	      //记录该id的预算投入涉及到的预算子项目
	      CostAccountReg costReg = costAccountRegMapper.selectByPrimaryKey(id);
	      List<Integer> costBudgetSubItemIds = new ArrayList();
	      if(CollectionUtil.isNotEmpty(costReg.getCostAccountRecords())){
		      List<CostAccountRecord> costAccountRecords = costAccountReg.getCostAccountRecords();
		      for(CostAccountRecord costAccountRecord:costAccountRecords){
		    	  costBudgetSubItemIds.add(costAccountRecord.getBudgetItemId());
		      }
	      }
	      
	      //作废
	      costAccountReg.setCancel(1);
	      costAccountReg.setModifyDate(new Date());
	      costAccountReg.setModifyId(MyShiroUtils.getSessionUserId());
	      int res = costAccountRegMapper.updateByPrimaryKeySelective(costAccountReg);
	      if(res==0){
	    	  result.setFalse("作废失败");
		      return result;
	      }
	      
	       costAccountRecordMapper.cancelByRegId(id);

	      if(CollectionUtil.isNotEmpty(costReg.getCostAccountRecords())){
		      //更新各预算项目投入金额
		      for(Integer costBudgetSubItemId:costBudgetSubItemIds){
		    	  updateItemByRecord(costBudgetSubItemId);
		      }
	      }
	      return result;
	  }
      
	  
	  public Result find(CostAccountReg costAccountReg) {
	      Result result = new Result();
	      PageHelper.startPage(costAccountReg.getPageCurrent(), costAccountReg.getPageSize());
	      List<CostAccountReg> costAccountRegs = costAccountRegMapper.search(costAccountReg);
	      result.setData(new PageInfo<>(costAccountRegs));

	      return result;
	  }
	  
	  public Result findDetail(CostAccountReg costAccountReg) {
	      Result result = new Result();
	      PageHelper.startPage(costAccountReg.getPageCurrent(), costAccountReg.getPageSize());
	      List<CostAccountReg> costAccountRegs = costAccountRegMapper.searchDetail(costAccountReg);
	      result.setData(new PageInfo<>(costAccountRegs));

	      return result;
	  }
	  
	  public Result show(int id) {
	      Result result = new Result();
	      CostAccountReg costAccountReg = costAccountRegMapper.show(id);
	      result.setData(costAccountReg);

	      return result;
	  }
	  
	  
	  
	  public Result searchByYear(Date year) {
	      Result result = new Result();
	      if(ObjectUtil.isNull(year)){
	    	  result.setFalse("年份不能为空");
		      return result;
	      }
	      int companyId = MyShiroUtils.getCompanyId();
	      List<CostAccountReg> costAccountRegs = costAccountRegMapper.searchDetailByYear(year,companyId);
	      if(CollectionUtil.isEmpty(costAccountRegs)){
	    	  result.setFalse("无该年份投入记录");
		      return result;
	      }else if(costAccountRegs.size()>1){
	    	  result.setFalse("该年份有多个投入记录，请检查");
		      return result;
	      }else{
		      result.setData(costAccountRegs.get(0));
	      }

	      return result;
	  }
}
